<?php
namespace app\common\model;

use think\Db;
use think\Model;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Config as tpConfig;
/* 用法一： 单条sql执行
    self::beginTrans();
    try{
        //$res= update;
        //self::commitTrans(); 
    }catch (\Exception $e){ // use think\Exception;
        self::rollbackTrans();
        return self::setErrorInfo(['line'=>$e->getLine(),'message'=>$e->getMessage()]);
    }
*/
/* 用法二： 多条sql执行
    self::beginTrans();
    $res1 = false !== UPDATE;
    $res2 = false !== INSERT;
    $res = $res1 && $res2;
    self::checkTrans($res);
    if(!$res) return self::setErrorInfo('申请退款失败!');
*/
/* 用法三： 循环提交
 self::beginTrans();
 try{
	foreach ($list as $k => $v)
	{
		$r1 = == UPDATE;
		$r2 = == INSERT;
		$r3 = == INSERT;
		self::commitTrans();
		$success++;
	}
 }catch(\think\Exception $e){
	self::rollbackTrans();
 }
*/
class ModelBasic extends Model
{
    private static $errorMsg;

    private static $transaction = 0;

    private static $DbInstance = [];

    const DEFAULT_ERROR_MSG = '操作失败,请稍候再试!';

    //连接诊所门店分库 $clinicId = 诊所id, $name = 不带前缀的表名
    public static function getSplitDb($clinicId = 0, $name = '')
    {
        $dbCfg = tpConfig::pull('split_db');
        // 数据库名 重新定义
        $dbCfg['database'] = $dbCfg['database'] . $clinicId;
        $dblink = Db::connect($dbCfg);
        return !$name ? $dblink : $dblink->name(trim($name));
    }

    protected static function getDb($name,$update = false)
    {
        if(isset(self::$DbInstance[$name]) && $update == false)
            return self::$DbInstance[$name];
        else
            return self::$DbInstance[$name] = Db::name($name);
    }

    /**
     * 设置错误信息
     * @param string $errorMsg
     * @return bool
     */
    protected static function setErrorInfo($errorMsg = self::DEFAULT_ERROR_MSG,$rollback = false)
    {
        if($rollback) self::rollbackTrans();
        self::$errorMsg = $errorMsg;
        return false;
    }

    /**
     * 获取错误信息
     * @param string $defaultMsg
     * @return string
     */
    public static function getErrorInfo($defaultMsg = self::DEFAULT_ERROR_MSG)
    {
        return !empty(self::$errorMsg) ? self::$errorMsg : $defaultMsg;
    }

    /**
     * 开启事务
     */
    public static function beginTrans()
    {
        Db::startTrans();
    }

    /**
     * 提交事务
     */
    public static function commitTrans()
    {
        Db::commit();
    }

    /**
     * 关闭事务
     */
    public static function rollbackTrans()
    {
        Db::rollback();
    }

    /**
     * 根据结果提交滚回事务
     * @param $res
     */
    public static function checkTrans($res)
    {
        if($res){
            self::commitTrans();
        }else{
            self::rollbackTrans();
        }
    }



    /**
     * 开启事务----诊所门店分库
     */
    public static function beginTransClinic($clinicId = 0)
    {
        self::getSplitDb($clinicId)->startTrans();
    }
    /**
     * 提交事务----诊所门店分库
     */
    public static function commitTransClinic($clinicId = 0)
    {
        self::getSplitDb($clinicId)->commit();
    }
    /**
     * 关闭事务----诊所门店分库
     */
    public static function rollbackTransClinic($clinicId = 0)
    {
        self::getSplitDb($clinicId)->rollback();
    }
    /**
     * 根据结果提交滚回事务----诊所门店分库
     * @param $res
     */
    public static function checkTransClinic($res = false,$clinicId = 0)
    {
        if($res){
            self::getSplitDb($clinicId)->commit();
        }else{
            self::getSplitDb($clinicId)->rollback();
        }
    }


    /**
    *检测表中字段是否唯一 return true = 存在， false = 不存在
    */
    public static function checkUniqueCode($model = null, $num = '', $fields = '')
    {
		if(empty($model) || !$num || !$fields) return false;
		$id = (int)$model::where([$fields => trim($num)])->count();
		return intval($id) > 0 ? true : false;
    }
	
}